﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Medianamik.Core.Logging
{
   public  class ExceptionTableBuilder : TableBuilder 
    {
       public Exception Exception
       {
           get;
           private set;
       }

       public ExceptionTableBuilder(Exception pException)
       {
           Exception = pException;
       }

       protected override void Build(XElement table)
       {
           table.Add(BuildHeaderRow(Exception.GetType().Name, 2));

           table.Add(BuildRow("Message", Exception.Message, false));
           table.Add(BuildRow("Stack Trace", FormatStackTrace(Exception.StackTrace), false));

       }

       private XElement FormatStackTrace(string pStackTrace)
       {
           var span = new XElement("span");
           if (pStackTrace != null)
           {
               var lines = pStackTrace.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
               lines.Aggregate(span, (container, line) => { container.Add(new XText(line), new XElement("br")); return container; });
           }
           return span;
       }
    }
}
